package com.xiaoka.ins.corp.api.gpic.help;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;

import com.xiaoka.ins.corp.api.dto.request.PremiumCalculationParam;
import com.xiaoka.ins.corp.api.dto.request.RiskDto;
import com.xiaoka.ins.corp.api.dto.request.VehicleDto;
import com.xiaoka.ins.corp.api.gpic.dto.ResponseElementGPIC.TagsList.Tags;
import com.xiaoka.ins.corp.api.gpic.dto.ResponseElementGPIC.TagsList.Tags.Tag;
import com.xiaoka.ins.corp.api.gpic.dto.ResponseElementGPIC.TagsList.Tags.Tag.Definition;
import com.xiaoka.ins.corp.api.gpic.dto.RootElementGPIC;
import com.xiaoka.ins.corp.api.gpic.dto.VcodeEnum;
import com.xiaoka.ins.corp.api.gpic.dto.VehicleInfo;
import com.xiaoka.ins.corp.api.gpic.dto.VehicletypeJson;
import com.xiaoka.ins.corp.api.utils.BaseUtils;

/**
 *	
 *车险接口dto和典典dto的对象参数转换
 * @author zheng
 *
 */
public class DataConversion {
	
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	private static final String company = "gpic";
	
	/**
	 * 车型查询接口返回车辆信息dto转换为典典车辆dto列表
	 * @param vehicletype
	 * @return
	 */
	public static ArrayList<VehicleDto> getVehicleList(VehicletypeJson vehicletype){
		ArrayList<VehicleDto> vlist = new ArrayList<VehicleDto>();
		for(Map<String,String> list:vehicletype.getRows()){
			VehicleDto vehicle = new VehicleDto();
			String value = list.get("value");
			vehicle.setBrandName(value);
			vehicle.setVehicleId(list.get("key"));
			vehicle.setVehiclePower("0");
			vehicle.setVehicleSeat(0);
			vehicle.setVehicleQuality("0");
			vehicle.setExhaustMeasure(new BigDecimal(0));
			vehicle.setPurchasePriceIncludeTax(ParameterAcquisition.getPurchasePriceIncludeTax(value));
			vlist.add(vehicle);
		}
		return vlist;
	}
	
	
	/**
	 * 将保险公司105接口返回的险种参数转换为典典的险种dto
	 * @param response105
	 * @return
	 */
	public static Map<String,RiskDto> getRiskForm105Return(RootElementGPIC response105){
		Map<String,RiskDto> map105 = new HashMap<String, RiskDto>();
		for(Tags tags:response105.get_package().getResponse().getTagsList().getTags()){
			for(Tag tag:tags.getTag()){
				RiskDto risk = new RiskDto();
				HashMap<String,String> map = new HashMap<String,String>();
				for(Definition d:tag.getDefinition()){
					map.put(d.getName(), d.getValue());
				}
				if("optional".equals(tags.getType())&&StringUtils.isNotBlank(map.get("key"))){
					String value = ParameterAcquisition.getRiskValue(map);
					value = VcodeEnum.forceFlag.value.equals(map.get("key"))?"0":value;//交强险默认不投保
					String premium = map.get("premium");
					premium = BaseUtils.addDecimalPoint(premium);
					VcodeEnum vcodeEnum = VcodeEnum.getCodeByValue(map.get("key"));
					if(vcodeEnum!=null){
						risk.setCode(vcodeEnum.name());
						risk.setvCode(vcodeEnum.value);
						risk.setValue(StringUtils.isBlank(value)?null:new BigDecimal(value));
						risk.setPremium(StringUtils.isBlank(premium)?null:new BigDecimal(premium));
						map105.put(risk.getCode(), risk);
					}
				}
			}
		}
		return map105;
	}
	
	/**
	 * 整合用户选择险种 和 105接口返回的险种 
	 * 判断险种正确性  
	 * 生成110报价接口险种请求参数
	 * 
	 * @param riskList
	 * @param riskMap105Return
	 * @return
	 */
	public static List<RiskDto> getRequestRiskList(List<RiskDto> riskList,Map<String,RiskDto> riskMap105Return){
		List<RiskDto> requestList = new ArrayList<RiskDto>();
		RiskDto m01Risk = null;
		if(riskMap105Return==null){
			riskMap105Return = new HashMap<String,RiskDto>();
			for(VcodeEnum v:VcodeEnum.values()){
				if(!VcodeEnum.bizFlag.name().equals(v.value)){
					riskMap105Return.put(v.name(), new RiskDto(v.name(),v.value, new BigDecimal(0), null));
				}
			}
		}else{
			m01Risk=riskMap105Return.get(VcodeEnum.M01.name());
		}
		for(RiskDto c:riskList){
			if(m01Risk!=null&&VcodeEnum.M01.name().equals(c.getCode())&&!"0".equals(c.getValue())){
				riskMap105Return.put(c.getCode(), new RiskDto(VcodeEnum.M01.name(),VcodeEnum.M01.value,m01Risk.getValue(),null));
			}else if(StringUtils.isNotBlank(c.getCode())){
				RiskDto risk = riskMap105Return.get(c.getCode());
				if(risk!=null){
					risk.setValue(c.getValue());
					riskMap105Return.put(c.getCode(), risk);
				}else{
					throw new RuntimeException("此险种不能投保："+c.getCode());
				}
			}
		}
		for(Entry<String,RiskDto> entry:riskMap105Return.entrySet()){
			requestList.add(entry.getValue());
		}
		return requestList;
	}
	
	/**
	 * 根据典典请求参数生成105接口参数集
	 * @param pc
	 * @return
	 */
	public static Map<String,String> get105RequestMap(PremiumCalculationParam pc){
		Map<String,String> map = new HashMap<String,String>();
		map.put(VehicleInfo.engineNo.name(),pc.getCustomerDto().getEngineNo());//发动机号
		map.put(VehicleInfo.vehicleFrameNo.name(),pc.getCustomerDto().getVehicleFrameNo());//车架号
		map.put(VehicleInfo.fuelType.name(),"A");   //车辆能源种类
		map.put(VehicleInfo.averageMile.name(),"28000");//年平均行驶里程
		map.put(VehicleInfo.vehicleInvoiceDate.name(),dateFormat.format(pc.getCustomerDto().getFirstReg()));//购车发票日期
		map.put(VehicleInfo.runCardCertificateDate.name(),dateFormat.format(pc.getCustomerDto().getTransferDate()));//发证日期
		map.put(VehicleInfo.firstRegisterDate.name(),dateFormat.format(pc.getCustomerDto().getFirstReg()));//注册登记日期
		map.put(VehicleInfo.forceBeginDate.name(),dateFormat.format(pc.getCustomerDto().getBegin()));//交强险生效日期
		map.put(VehicleInfo.bizBeginDate.name(),dateFormat.format(pc.getCustomerDto().getBegin()));//商业险生效日期
		map.put(VehicleInfo.ownerName.name(),pc.getCustomerDto().getName());//车主姓名
		String specialCarFlag = "";
		String specialCarDate = "";
		if(!pc.getCustomerDto().getTransferDate().equals(pc.getCustomerDto().getFirstReg())){
			specialCarDate = dateFormat.format(pc.getCustomerDto().getTransferDate());//过户日期
			specialCarFlag = "1";
		}else{
			specialCarFlag = "0";
		}
		map.put(VehicleInfo.specialCarDate.name(),specialCarDate);//过户日期
		map.put(VehicleInfo.specialCarFlag.name(),specialCarFlag);//是否过户车  1：是，0：否
		map.put(VehicleInfo.vehicleModelName.name(),pc.getVehicleDto().getBrandName());//品牌型号
		map.put(VehicleInfo.vehicleId.name(),pc.getVehicleDto().getVehicleId());//车辆ID
		map.put(VehicleInfo.payNo.name(),"");//完税凭证号
		map.put(VehicleInfo.vehicleCodeName.name(),pc.getVehicleDto().getBrandName());
		map.put(VehicleInfo.vehicleCodeId.name(),pc.getVehicleDto().getVehicleId());
		return map;
	}
	
	/**
	 * 将保险公司110接口返回的险种参数转换为典典的险种dto
	 * @param response110
	 * @return
	 */
	public static Map<String,RiskDto> getRiskListForm110Return(RootElementGPIC response110){
		Map<String,RiskDto> map110 = new HashMap<String, RiskDto>();
		for(Tags tags:response110.get_package().getResponse().getTagsList().getTags()){
			for(Tag tag:tags.getTag()){
				RiskDto risk = new RiskDto();
				HashMap<String,String> map = new HashMap<String,String>();
				for(Definition d:tag.getDefinition()){
					map.put(d.getName(), d.getValue());
				}
				if("deadline".equals(tags.getType())){
					risk.setValue(new BigDecimal(map.get("value").replace("-", "")));
				}else if("optional".equals(tags.getType())||"force".equals(tags.getType())) {
					String value = ParameterAcquisition.getRiskValue(map);
					String premium = map.get("premium");
					premium = BaseUtils.addDecimalPoint(premium);
					risk.setValue(StringUtils.isBlank(value)?null:new BigDecimal(value));
					risk.setPremium(StringUtils.isBlank(premium)?null:new BigDecimal(premium));
				}
				if(StringUtils.isNotBlank(map.get("key"))){
					VcodeEnum vcodeEnum = VcodeEnum.getCodeByValue(map.get("key"));
					risk.setvCode(map.get("key"));
					risk.setCode(vcodeEnum!=null?vcodeEnum.name():risk.getvCode());
					map110.put(risk.getCode(), risk);
				}
			}
		}
		return map110;
	}
	
	/**
	 * 根据用户请求参数和报价接口返回参数  获取报价持久化到mongo的参数
	 * @param pc
	 * @param response
	 * @return
	 */
	public static PremiumCalculationParam getPremiumCalculationPersistence(PremiumCalculationParam pc, RootElementGPIC response){
		Map<String,RiskDto> map110 = getRiskListForm110Return(response);
		List<RiskDto> covList = new ArrayList<RiskDto>();
		for(RiskDto r:pc.getRiskDtoList()){
			if(StringUtils.isNotBlank(r.getCode())){
				if(VcodeEnum.forceFlag.value.equals(r.getCode())){
					r.setPremium(map110.get("forceTotalPremium").getPremium());
					r.setvCode(r.getCode());
					covList.add(r);
				}else{
					if(map110.get(r.getCode())!=null){
						covList.add(map110.get(r.getCode()));
					}
				}
			}
		}
		List<RiskDto> saveList = new ArrayList<RiskDto>(covList);
		saveList.add(map110.get("vehicleTaxPremium"));
		saveList.add(map110.get("forcePremium"));
		saveList.add(map110.get("forceTotalPremium"));
		saveList.add(map110.get("bizTotalPremium"));
		saveList.add(map110.get("totalPremium"));
		saveList.add(map110.get("standardPremium"));
		pc.setRiskDtoList(saveList);
		pc.setId(response.get_package().getHeader().getSessionId());
		pc.getCustomerDto().setBegin(DateUtils.parseDate(map110.get("forceBeginDate").getValue().toString(),new String[]{"yyyyMMdd"}));
		pc.setCompany(company);
		pc.getVehicleDto().setPurchasePriceIncludeTax(map110.get(VcodeEnum.M01.name()).getValue().toString());
		return pc;
	}
	
}
